window['bgOpts'] = {page:"Contract"}
//标识是否停止导入
var isStop = true;
var $progress = undefined;
+function(){
	//后台获取是否显示带入按钮
	bgOpts.method="GetShowContractImport";
	bg.getInfo(function(resp){
		if(resp.obj){
			//添加按钮
			$btnBatch = $(t.replaceParams(t.panelButton,{text:"导入文件[秋版]"}));
			$("#btn_list").append($btnBatch);
			//添加停止按钮,添加到父窗口
			$btnStop = $(t.replaceParams(t.panelButton,{text:"停止导入[下一个将会停止]",id:"btnStop"}));
			$("body").append($btnStop);
			//添加查看最后一次导入记录按钮
			$btnShowLastLog = $(t.replaceParams(t.panelButton,{text:"最后一次导出结果",id:"btnLastLog"}));
			$("body").append($btnShowLastLog);
			
			//添加批处理按钮的点击事件
			$btnBatch.click(function(){
				that = $(this);
				//弹出导入事件
				$("<input type='file'/>").change(function(ev){
					if(ev.target.files.length>0){
						e.importXlsxToJSON(ev.target.files[0],function(res){
							var list = [];
							//导入excel到json，然后将json转出后续处理的json
							for(var i in res){
								var tmp = res[i];
								var dt = new Date();
								var payTime = tmp['打款时间']?c.getExcelDate(tmp['打款时间']).format("yyyy-MM-dd")+" "+dt.getHours()+":"+dt.getMinutes():"";
								var obj = {
									TextOne:(tmp['开户单']||"").toUpperCase(),
									PayTime:payTime,
									ReceivedAccoun:tmp['收款账户']||"",
									PayAmount:tmp['金额']==undefined?"":tmp['金额'],
									ReceivedCompany:tmp['收款公司']||"",
									ReceivedType:tmp['凭证收取方式']||"",
									Description:tmp['备注']||"",
									TransactionNo:tmp['交易单号']||"0000",
								};
								list.push(obj);
							}
							//开始之前清空后台的错误列表
							bgOpts.method="ClearContractError";
							bg.getInfo(function(resp){
								isStop = false;
								//添加进度条
								$progress = addProgress(200,list.length,0);
								importBatchExecute(list,0,that);
							});
						});
					}
				}).click();
			});
			//添加停止的点击事件
			$btnStop.click(function(){
				if(isStop){
					c.showInfo("没有正在执行的进度");
				}else{
					isStop = true;
				}
			});
			//最后一次导出记录按钮的点击事件
			$btnShowLastLog.click(function(){
				//获取错误列表
				bgOpts.method = "GetContractError";
				bg.getInfo(function(resp){
					if(resp.code == 400){
						
						if(resp.obj == undefined || resp.obj.length <= 0){
							c.showError("您尚未导入任何记录!","提示");
						}else{
							var tip = "";
							tip+="最后一次处理结果：<br/>";
							for(var i = 0; i < resp.obj.length;i++){
								var obj = resp.obj[i];
								tip+=obj.errorMsg+"<br/>";
							}
							//对话框添加导出按钮
							var btns = [{
								text:"详细结果",
								click:function(){
									e.downloadJson(resp.obj,"当前合同批量确认结果.xlsx");
								}
							}];
							c.showInfo(tip,"结果记录",btns);
						}
					}
				});
			})
		}
	});
	
	
}();
//ContractSureReceipt对话框是否已关闭
IsContractSureReceiptClosed = true;
//导入执行，list是执行的文件列表，i是当前的序号
function importBatchExecute(list,handle,elem){
	//等待ContractSureReceipt对话框关闭
	var waitInterval = setInterval(function(list,handle){
		//判断ContractSureReceipt是否已关闭
		if(IsContractSureReceiptClosed){
			//停止等待关闭对话框的循环
			clearInterval(waitInterval);
			//判断循环是否结束并且没有停止
			if(handle < list.length&&!isStop){
				c.log("----------------------------");
				c.log("开始处理第"+(handle+1)+"/"+list.length+"条记录");
				p.setProgressValue($progress,handle+1)
				var obj = list[handle];
				//判断是否有合同号
				if(obj.TextOne!=""){
					/*----------搜索合同单号 开始---------*/
					//下拉框选择合同单号
					$("#SelectOne").val("BillNo");
					//设置合同单号
					$("#TextOne").val(obj.TextOne);
					//点击搜索
					$("#btnSearch").click();
					/*----------搜索合同单号 结束---------*/
					/*----------搜索之后遍历结果 开始---------*/
					var waitCount = 0;//等待次数
					var index = setInterval(function(obj){
						waitCount++;
						//判断loading效果是否消失
						if($("#maingrid .l-grid-loading").css("display")!="none"){
							//loading没消失，说明正在查询
							c.log("正在查询中...");
							return;
						}
						var data = c.getTableData("maingrid");
						c.log("查询到结果："+data.length);
						var i = 0;
						for(i = 0; i < data.length;i++){
							//判断合同号是否一致
							var id = $(c.getTableCell("maingrid",i,2)).find("div").html();
							if(id == obj.TextOne){
								//获取确认收款元素
								$el = $(c.getTableCell("maingrid",i,29)).find("input[value=确认收款]");
								c.log("搜索结果已匹配，按钮个数:"+$el.length);
								//判断是否有确认收款按钮
								if($el.length>0){
									clearInterval(index);
									//将obj保存至bg的localStorage
									bgOpts.method="SetContractInfo";
									bgOpts.obj = obj;
									bg.getInfo(function(resp){
										if(resp.code == 400){
											IsContractSureReceiptClosed = false;
											//点击弹出对话框
											$el.click();
										}
										//继续下一次
										importBatchExecute(list,handle+1);
										
									});
									break;
								}
							}
						}
						//如果没有带确认收款按钮的行，并且等待次数已达上限
						if(i >= data.length&&waitCount > cfg.waitContractSearchCount){
							clearInterval(index);
							contractSubmitError(obj,"查询结果中没有确认收款按钮");
							//继续下一次
							importBatchExecute(list,handle+1);
						}
					},500,obj);
					/*----------搜索之后遍历结果 结束---------*/
				}else{
					contractSubmitError(obj,"合同号为空");
					//继续下一次
					importBatchExecute(list,handle+1);
				}
			}else{
				//删除进度条
				$progress.parent().remove();
				var tip = "结束方式：";
				if(isStop){
					tip = "停止按钮结束<br/>";
				}else{
					//所有循环完毕
					tip = "处理完毕结束<br/>";
				}
				//获取错误列表
				bgOpts.method = "GetContractError";
				bg.getInfo(function(resp){
					if(resp.code == 400){
						if(isStop){
							tip+="已确认："+handle+"/"+list.length+" &nbsp;条<br/>";
						}
						tip+="确认错误："+resp.obj.length+"/"+handle+" &nbsp;条<br/>";
						tip+="处理结果：<br/>";
						for(var i = 0; i < resp.obj.length;i++){
							var obj = resp.obj[i];
							tip+=obj.errorMsg+"<br/>";
						}
						//对话框添加导出按钮
						var btns = [{
							text:"详细结果",
							click:function(){
								e.downloadJson(resp.obj,"当前合同批量确认结果.xlsx");
							}
						}];
						if(resp.obj.length > 0){
							c.showError(tip,"错误",btns);
						}else{
							c.showInfo(tip,"结果记录",btns);
						}
						//设置stop
						isStop = true;
					}
				});
			}
		}
	},500,list,handle);
}
function CloseContractSureReceipt(){
	IsContractSureReceiptClosed = true;
	$(".l-dialog:last").css("display","none");
	$(".l-window-mask").css("display","none");
}
//合同提交错误，向后台发送错误消息
function contractSubmitError(obj,Msg,success){
	success=success||false;
	var m = "["+obj.TextOne+"]:"+Msg;
	c.warn(m);
	bgOpts.method="AddContractError";
	obj.success=success;
	obj.errorMsg = m;
	//错误提交到后台
	bgOpts.obj=obj;
	bg.getInfo(function(resp){});
}
function addProgress(width,max,value){
	width = width||200;
	//页面增加进度条
	$("#maingrid .l-panel-bar .l-panel-bbar-inner .l-clear").remove();
	$div = $("<div class='l-bar-group'></div>");
	$("#maingrid .l-panel-bar .l-panel-bbar-inner").append($div);
	return p.init({
		parentElem:$div,
		width:width,
		max:max,
		value:value
	});
}
